<!DOCTYPE html>
<html>

<head>
  <title>WebGPU canvas' capture as video stream test</title>
  <style type="text/css">
    .nomargin {
      margin: 0px auto;
    }
  </style>
  <script type="text/javascript" src="pixel_webgpu_util.js"></script>
  <script type="text/javascript">
    var g_swapsBeforeAck = 15;
    var g_videoFrameReceived = false;

    const parsedString = new URLSearchParams(window.location.search);

    async function main() {
      const has_alpha_string = parsedString.get('has_alpha');

      has_alpha = (has_alpha_string != null) ?
        has_alpha_string == 'true' : false;

      const gpuCanvas = document.getElementById('canvas_gpu');
      const [device, swapChain] = await webGpuUtils.init(gpuCanvas, /*has_alpha=*/has_alpha);
      if (!device || !swapChain) {
        console.error("Failed to initialize WebGPU - skipping test");
        domAutomationController.send("FAILURE");
        return;
      }

      const video = document.getElementById('video_player');
      video.srcObject = gpuCanvas.captureStream();

      function render() {
        const gpuContext = gpuCanvas.getContext('webgpu');

        webGpuUtils.fourColorsTest(device, swapChain, gpuCanvas.width,
          gpuCanvas.height);

        waitForFinish();
      }

      function videoFrameReceived() {
        g_videoFrameReceived = true;
      }

      function waitForFinish() {
        if (g_swapsBeforeAck == 0) {
          domAutomationController.send("SUCCESS");
        } else {
          // only start count down when a video frame has been received
          if (g_videoFrameReceived)
            g_swapsBeforeAck--;
          window.requestAnimationFrame(render);
        }
      }

      // Start rendering loop
      window.requestAnimationFrame(render);

      // register a callback to be invoked when a video frame has been received.
      if (video.requestVideoFrameCallback) {
        video.requestVideoFrameCallback(videoFrameReceived);
      }
      else {
        // requestVideoFrameCallback not available
        g_videoFrameReceived = true;
      }
    }
  </script>
</head>

<body onload="main()">
  <video id="video_player" playsinline autoplay muted width="200" height="200" class="nomargin"></video>
  <canvas id="canvas_gpu" width="200" height="200" class="nomargin"></canvas>
</body>

</html>